//
//  TL_UserInfoModel.m
//  WXReader
//
//  Created by LL on 2020/6/5.
//  Copyright © 2020 Andrew. All rights reserved.
//

#import "TL_UserInfoManager.h"
#import "NSObject+Utils.h"

@implementation TL_UserInfoManager

+ (void)initialize {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:WXUserInfoManagerLogoutNotification object:nil];
}

+ (BOOL)isLogin {
    NSString *tokenStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"];
    return !kObjectIsEmpty(tokenStr);
}

+ (BOOL)isVip {
    return TL_UserInfoManager.userInfo.userVip.intValue != 0;
}

+ (void)logout {
    if (!TL_UserInfoManager.isLogin) return;
    
    [TL_UserInfoManager.userInfo dynamicInit];
    [NSFileManager.defaultManager removeItemAtPath:TL_UserInfoModel.userInfoPath error:nil];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userToken"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserInfoModelDict"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSNotificationCenter.defaultCenter postNotificationName:WXUserInfoManagerDidLogoutNotification object:nil];
    });
}

+ (TL_UserInfoModel *)userInfo {
    return TL_UserInfoModel.shareInstance;
}

static NSDictionary<NSString *, NSString *> *_property;
+ (TL_UserInfoModel * _Nonnull (^)(NSDictionary * _Nonnull userDataDic))updateWithDict {
    return ^(NSDictionary *dict) {
        if (!TL_UserInfoManager.isLogin) return TL_UserInfoModel.shareInstance;
        
        _property = _property ?: TL_UserInfoModel.propertyDict;
        NSDictionary *t_dict = TL_UserInfoModel.modelCustomPropertyMapper;
        
        for (NSString *key in _property) {
            id t_name = t_dict[key];
            id value = nil;
            
            // 处理映射关系
            if ([t_name isKindOfClass:[NSArray class]]) {
                // 遍历数组中的键，取第一个存在的值
                for (NSString *mapKey in t_name) {
                    value = dict[mapKey];
                    if (value && ![value isKindOfClass:[NSNull class]]) {
                        break;
                    }
                }
            } else if ([t_name isKindOfClass:[NSString class]]) {
                value = dict[t_name];
            } else {
                if ([_property[key] isEqualToString:@"NSString"]) {
                    value = [NSString stringWithFormat:@"%@",dict[key]];
                }else if ([_property[key] isEqualToString:@"TLSocialLoginModel"]){
                    value = [TLSocialLoginModel mj_objectWithKeyValues:dict[key]];
                    
                    if (!value || [value isKindOfClass:[NSNull class]]) {
                        // 使用KVC安全设置值（自动处理类型转换）
                        @try {
                            [TL_UserInfoModel.shareInstance setValue:value forKey:key];
                        } @catch (NSException *exception) {
                            NSLog(@"设置属性%@失败: %@", key, exception.reason);
                        }
                    }
                    
                }
                else{
                    value = dict[key];
                }
            }
            
            
            
            // 过滤无效值
            if (!value || [value isKindOfClass:[NSNull class]]) continue;
            
            // 使用KVC安全设置值（自动处理类型转换）
            @try {
                [TL_UserInfoModel.shareInstance setValue:value forKey:key];
            } @catch (NSException *exception) {
                NSLog(@"设置属性%@失败: %@", key, exception.reason);
            }
        }
        
        // 持久化存储
        NSDictionary *jsonDict = [TL_UserInfoManager.userInfo modelToJSONObject];
        if ([jsonDict writeToFile:TL_UserInfoModel.userInfoPath atomically:YES]) {
            NSLog(@"用户信息保存成功");
        } else {
            NSLog(@"用户信息保存失败，路径: %@", TL_UserInfoModel.userInfoPath);
        }
        
        
        return TL_UserInfoModel.shareInstance;
    };
}

@end
